﻿// this content-script plays role of medium to publish/subscribe messages from webpage to the background script

var RTC_PAGE_MSG_TYPE = 'RTC-SD-PAGE';
var RTC_EXT_MSG_TYPE = 'RTC-SD-EXT';

// this port connects with background script
var port = chrome.runtime.connect();

// if background script sent a message
port.onMessage.addListener(function (message) {
    // get message from background script and forward to the webpage
    window.postMessage(message, '*');
});

// this event handler watches for messages sent from the webpage
// it receives those messages and forwards to background script
window.addEventListener('message', function (event) {
    // if invalid source
    if (event.source != window) return;
        
    if(!event.data) return;
    if(!event.data.type || event.data.type !== RTC_PAGE_MSG_TYPE) return;
    if(!event.data.evname) return;

    console.log('rtc-sd-content: forward data=', event.data);
    port.postMessage(event.data);

});


var num_loads_ = 0;
// console.log('rtc shard desktop loaded, num=', num_loads_, ', window=', window);
num_loads_++;

var existelm = document.createElement('div');
existelm.id = 'RTC-Share-Deskto-installed-ele-rat1abrr';
existelm.style.display = 'none';
(document.body || document.documentElement).appendChild(existelm);


// inform browser that I'm available!
window.postMessage({type:RTC_EXT_MSG_TYPE, evname:'extLoaded'}, '*');
